<?php

declare(strict_types=1);

namespace App\Services;

use App\Inc\AdvertInc;
use App\Inc\OrderInc;
use App\Models\Advert;
use App\Models\AdvertImage;
use App\Utils\ImageUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class AdvertService
{
    /**
     * @param $cityId
     * @param $positionId
     *
     * @return array
     */
    public function getAd(int $cityId, int $positionId)
    {
        $advert = Advert::where([
            'city_id'     => $cityId,
            'position_id' => $positionId,
            'status'      => OrderInc::ADVERT_STATUS_开启,
        ])->first();
        Log::debug('广告位读取 城市配置 ' . $cityId . ' ' . $positionId);

        //走默认图片配置
        if (empty($advert)) {
            $advert = Advert::where([
                'city_id'     => 0,
                'position_id' => $positionId,
                'status'      => OrderInc::ADVERT_STATUS_开启,
            ])->first();
            Log::debug('广告位读取 默认配置 0 ' . $positionId . ' ');
        }

        $advert_image = [];
        if ($advert) {
            $currentTime = Carbon::now()->timestamp;

            $advert_image_temp = AdvertImage::where([
                'advert_id'          => $advert->id,
                'advert_status'      => AdvertInc::ADVERT_STATUS_正常,
                'upper_lower_status' => 1,
            ])->orderby('advert_sort')
                ->get();

            Log::debug('广告位读取 ' . count($advert_image_temp) . ' 条 数据' . $cityId . ' ' . $currentTime . ' ' . $advert->id);

            if ($advert_image_temp) {
                $advert_image = $advert_image_temp->toArray();
                foreach ($advert_image as $key => $value) {
                    $advert_image[$key]['image'] = ImageUtil::groupImageUrl($value['image']);
                }
            }
        }

        if (empty($advert_image)) {  // 返回默认图片
            $advert_image[0]['advert_title'] = '';
            $advert_image[0]['advert_url']   = '';
            $advert_image[0]['image']        = env('APP_URL') . '/default_banner01.png';
        }

        return $advert_image;
    }
}
